package com.nobug.service.brand;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nobug.bean.BaseRespVo;
import com.nobug.bean.brand.Brand;
import com.nobug.bean.brand.VO.BrandCreateVO;
import com.nobug.bean.brand.VO.BrandListVO;
import com.nobug.bean.brand.BrandExample;
import com.nobug.mapper.brandMapper.BrandMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BrandServiceImpl implements BrandService{
    @Autowired
    BrandMapper mapper;

    /*brandList接口*/
    @Override
    public BaseRespVo<BrandListVO> queryBrands(Integer page, Integer limit, String sort, String order) {
        /*引入分页插件，来做分页, 分页插件就是给我们的sql预编译语句，添加page， 和limit， 使用分页查询，需要告诉springboot我们使用的数据库是mysql*/
        Page<Object> objects = PageHelper.startPage(page, limit);
        BrandExample brandExample = new BrandExample();
        brandExample.setOrderByClause(sort + " " + order);
        List<Brand> brands = mapper.selectByExample(brandExample);
        /*获取分页信息，起始页，size，total等*/
        PageInfo<Brand> brandPageInfo = new PageInfo<>(brands);
        long total = brandPageInfo.getTotal();
        /*此时排序查找已经执行，分页也完成，需要创建一个BrandListVO*/
        BrandListVO brandListVO = BrandListVO.getInstance(total, brands);
        BaseRespVo<BrandListVO> results = BaseRespVo.ok(brandListVO);
        return results;
    }

    /*brandCreate接口*/
    @Override
    public BaseRespVo<BrandCreateVO> brandInsert(Brand brand) {
        Integer lastInsertId = mapper.insertSelective(brand);
        BrandCreateVO brandCreateVO = mapper.selectByPrimaryKey(lastInsertId);
        BaseRespVo<BrandCreateVO> brandCreateVOBaseRespVo = BaseRespVo.ok(brandCreateVO);
        return brandCreateVOBaseRespVo;
    }

    @Override
    public BaseRespVo<BrandListVO> queryBrands(Integer page, Integer limit, String sort, String order, Integer id, String name) {
        Integer offset = (page - 1) * limit;
        List<Brand> brands = mapper.selectListByIdOrName(offset, limit, sort, order, id, name);
        PageInfo<Brand> brandPageInfo = new PageInfo<>(brands);
        long total = brandPageInfo.getTotal();
        /*此时排序查找已经执行，分页也完成，需要创建一个BrandListVO*/
        BrandListVO brandListVO = BrandListVO.getInstance(total, brands);
        BaseRespVo<BrandListVO> results = BaseRespVo.ok(brandListVO);
        return results;
    }

    @Override
    public void deleteBrand(Brand brand) {
        mapper.deleteByPrimaryKey(brand.getId());
    }
}
